import React, {useEffect, useState, useMemo} from 'react'
import {ProColumns} from '@ant-design/pro-components'
import {Button, Form, Space, Modal, Popconfirm} from 'antd'
import moment from 'moment'
import {connect} from 'umi'
import type {UploadFile} from 'antd/es/upload/interface'
import CustomTable from '@/components/Table'
import FormV from './formV'
import {
	geTditchReplenishList,
	getNoCS,
} from '@/service/merchantCenter/channelSettlement'
import Styles from './index.less'
import {getPublicDownloadUrl} from '@/service/common/upload'

type DataSourceType = {
	urlName: string
	href: string | undefined
	id: React.Key
	title?: string
	labels?: {
		key: string
		label: string
	}[]
	state?: string
	// eslint-disable-next-line camelcase
	created_at?: string
	children?: DataSourceType[]
}

const data = [
	{id: '1', name: '渠道sp'},
	{id: '2', name: '车司'},
	{id: '3', name: '自营-BD'},
	{id: '4', name: '自营-司推司'},
	{id: 5, name: '自营-普推司'},
]

const eidtable = ({
	clueId,
	detailRecord,
	tableList,
	setTableList,
	channelTypeOneType,
	pageType,
	user,
}: any) => {
	const [formData, setFormData] = useState({})
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	const [loading, setLoading] = useState(false)
	const [visible, setVisible] = useState(false)
	const [type, setType] = useState('')
	const [cid, setCid] = useState('')
	const [did, setDid] = useState('')
	const [fileList, setFileList] = useState<UploadFile[]>([])

	useEffect(() => {
		getNoCS().then((res: any) => {
			if (res.success) {
				setDid(res.data)
			}
		})
	}, [detailRecord, visible])

	const [form] = Form.useForm()

	const initialValues = useMemo(() => {
		let value: any = {}
		if (visible) {
			if (type === 'add') {
				value.cityName = detailRecord?.cityName
				value.ditchName = detailRecord?.ditchName
				value.orgName = detailRecord?.orgName
				value.replenishNo = did
			} else if (type === 'edit') {
				// value.cityName = detailRecord?.cityName
				// value.username = detailRecord?.username
				// value.orgName = detailRecord?.orgName
				value = tableList.find((item: any) => item.replenishNo === cid)
				value.rewardOccurrenceDate = moment(value.rewardOccurrenceDate)
				// value.fileIds = {
				// 	file: {
				// 		uid: '-1',
				// 		name: 11,
				// 		url: '11',
				// 		response: {
				// 			data: {
				// 				filename: '22',
				// 				url: '33',
				// 				giftNamespace: '44',
				// 				giftKey: value?.fileIds,
				// 			},
				// 		},
				// 	},
				// 	fileList: [
				// 		{
				// 			uid: '-1',
				// 			name: 22,
				// 			status: 'done',
				// 			url: '33',
				// 			response: {
				// 				data: {
				// 					filename: '44',
				// 					url: '55',
				// 					giftNamespace: '666',
				// 					giftKey: value?.fileIds,
				// 				},
				// 			},
				// 		},
				// 	],
				// }
			}
		}

		setTimeout(() => {
			form.resetFields()
		}, 1)
		return value
	}, [detailRecord, visible, did, cid])

	const getTabelValue = async (value: any, pagination?: any) => {
		setLoading(true)
		let values = value

		setFormData(values)
		const newPagination = pagination || {
			current: 1,
			size: params.size,
		}
		setParams(newPagination)
		values = {
			...values,
			// ...newPagination,
		}

		const res = await geTditchReplenishList({...values, id: clueId})
		if (res?.data) {
			setTotal(res.data?.total || 0)
			if (res.data?.records) {
				const datas = res.data?.records
				const urls = datas?.map(
					(item: {fileIds: string}) => item?.fileIds,
				)
				if (urls?.length) {
					getPublicDownloadUrl(urls).then((result: any) => {
						if (result?.success) {
							const newList = [...datas]
							newList?.forEach(
								(item: {fileIds: string}, index) => {
									const urlData = result?.data?.find(
										(items: {id: number}) =>
											items?.id === Number(item?.fileIds),
									)
									if (urlData) {
										datas[index].href = urlData?.url
										datas[index].urlName = urlData?.filename
									}
								},
							)
						}
					})
				}
				setTableList(datas || [])
			}
		}
		setLoading(false)
	}

	useEffect(() => {
		getTabelValue({})
	}, [clueId])

	const onSave = async () => {
		let FormD = await form.validateFields()

		FormD.rewardOccurrenceDate = moment(FormD.rewardOccurrenceDate).format(
			'YYYY-MM-DD HH:mm:ss',
		)
		const newList = JSON.parse(JSON.stringify(tableList))
		if (FormD?.fileIds) {
			FormD.fileIds =
				fileList?.[0]?.response?.data?.id || fileList?.[0]?.uid
			getPublicDownloadUrl([FormD.fileIds]).then((result: any) => {
				if (result?.success) {
					FormD.href = result?.data?.[0]?.url
					FormD.urlName = result?.data?.[0]?.filename
					FormD = {
						...FormD,
						...detailRecord,
						createUserName: user?.userName,
						supplementaryCostStatus: 1,
					}
					newList.push(FormD)
					setTableList(newList)
					setVisible(false)
				}
			})
		} else {
			FormD = {
				...FormD,
				...detailRecord,
				createUserName: user?.userName,
				supplementaryCostStatus: 1,
			}
			newList.push(FormD)
			setTableList(newList)
			setVisible(false)
		}
	}
	const onEdit = async () => {
		let FormD = await form.validateFields()
		FormD.rewardOccurrenceDate = moment(FormD.rewardOccurrenceDate).format(
			'YYYY-MM-DD HH:mm:ss',
		)
		const newList = JSON.parse(JSON.stringify(tableList))
		const index = newList.findIndex((item: any) => item.replenishNo === cid)
		if (FormD?.fileIds) {
			FormD.fileIds =
				fileList?.[0]?.response?.data?.id || fileList?.[0]?.uid
			getPublicDownloadUrl([FormD.fileIds]).then((result: any) => {
				if (result?.success) {
					FormD.href = result?.data?.[0]?.url
					FormD.urlName = result?.data?.[0]?.filename
					FormD = {
						...FormD,
						...detailRecord,
						createUserName: user?.userName,
						supplementaryCostStatus: 1,
					}
					newList[index] = FormD
					setTableList(newList)
					setVisible(false)
				}
			})
		} else {
			FormD = {
				...FormD,
				...detailRecord,
				createUserName: user?.userName,
				supplementaryCostStatus: 1,
			}
			newList[index] = FormD
			setTableList(newList)
			setVisible(false)
		}
	}
	const columns: ProColumns<DataSourceType>[] = [
		{title: '补扣费编码', dataIndex: 'replenishNo', align: 'center'},
		{title: '费用发生月份', dataIndex: 'expenseMouth', align: 'center'},
		{
			title: '奖励发生时间',
			dataIndex: 'rewardOccurrenceDate',
			align: 'center',
		},
		{title: '主体', dataIndex: 'subjectName', align: 'center'},
		{title: '公司', dataIndex: 'orgName', align: 'center'},
		{title: '城市', dataIndex: 'cityName', align: 'center'},
		{
			title: 'AMC一级渠道类型 ',
			dataIndex: 'firstLevelType',
			align: 'center',
			render: (text: any) => {
				const obj: any = channelTypeOneType?.find(
					(res: any) => res.type === text,
				)
				return obj?.valueName
			},
		},
		{
			title: 'AMC二级渠道类型',
			dataIndex: 'secondLevelType',
			align: 'center',
			render: (text: any) =>
				data?.map((res: any) => {
					if (text == res?.id) {
						return <span>{res?.name}</span>
					}
					return ''
				}),
		},
		{title: '渠道id', dataIndex: 'ditchId', align: 'center'},
		{title: '渠道名称', dataIndex: 'ditchName', align: 'center'},
		{
			title: '类型',
			dataIndex: 'rewardsType',
			align: 'center',
			render: (text: any) =>
				((
					{
						'1': '冲单',
						'2': '阶梯',
						'3': 'BD跟单费',
					} as any
				)[text]),
		},
		{title: '补费总金额', dataIndex: 'replenishCost', align: 'center'},
		{title: '补费拉新量', dataIndex: 'replenishCount', align: 'center'},
		{
			title: '补费总期数',
			dataIndex: 'replenishTerm',
			align: 'center',
			render: (text) => (text === 0 ? '-' : text),
		},
		{
			title: '单期拉新费',
			dataIndex: 'replenishCost/replenishTerm',
			align: 'center',
			render: (_, record: any) => {
				if (record?.rewardsType === 2) {
					let pullFee = 0
					if (record?.replenishTerm === 0 || !record?.replenishTerm) {
						pullFee = 0
					} else {
						pullFee =
							Number(record?.replenishCost) /
							Number(record?.replenishTerm)
					}
					return Number(pullFee?.toFixed(2))
				}
				return '-'
			},
		},
		{
			title: '补费理由',
			dataIndex: 'replenishReason',
			align: 'center',
			render: (text) => text || '-',
		},
		{
			title: '审核状态',
			dataIndex: 'supplementaryCostStatus',
			align: 'center',
			render: (text: any) =>
				((
					{
						'0': '无补扣',
						'1': '待审核',
						'2': '审核中',
						'3': '审核完成',
						'4': '审核驳回',
					} as any
				)[text]),
		},
		{
			title: '审核时间',
			dataIndex: 'checkTime',
			align: 'center',
			render: (text, record: any) =>
				record?.supplementaryCostStatus === '3' ||
				record?.supplementaryCostStatus === '4'
					? text
					: '-',
		},
		{title: '申请人', dataIndex: 'createUserName', align: 'center'},
		{title: '申请提交时间', dataIndex: 'createTime', align: 'center'},
		{
			title: '附件',
			dataIndex: 'fileIds',
			align: 'center',
			render: (_, record) => <a href={record?.href}>{record?.urlName}</a>,
		},
		{title: '备注', dataIndex: 'remark', align: 'center'},
		{
			title: '操作',
			valueType: 'option',
			fixed: 'right',
			render: (_: any, record: any) => (
				<>
					{record?.supplementaryCostStatus === 2 ||
					record?.supplementaryCostStatus === 3 ? (
						''
					) : (
						<Space size={12}>
							<Button
								type="link"
								disabled={pageType !== 'edit'}
								onClick={() => {
									setCid(record.replenishNo)
									setType('edit')
									setVisible(true)
								}}>
								编辑
							</Button>
							<Popconfirm
								placement="topLeft"
								title="你确定要删除这条线索数据吗？"
								onConfirm={async () => {
									const newList = tableList.filter(
										(item: any) =>
											item.replenishNo !==
											record.replenishNo,
									)
									setTableList(newList)
								}}
								okText="确定"
								cancelText="取消">
								<Button
									type="link"
									disabled={pageType !== 'edit'}>
									删除
								</Button>
							</Popconfirm>
						</Space>
					)}
				</>
			),
		},
	]

	console.log(tableList, 'tableList-----')

	return (
		<div className={Styles.basics}>
			<div className={Styles.titleBox}>补扣费</div>
			<>
				<Space
					style={{
						display: 'flex',
						justifyContent: 'end',
						marginRight: '60px',
						paddingTop: '15px',
						paddingBottom: '15px',
					}}>
					<Button
						type="primary"
						disabled={pageType !== 'edit'}
						onClick={() => {
							setType('add')
							setVisible(true)
						}}>
						新增
					</Button>
				</Space>

				<CustomTable
					params={params}
					columns={columns}
					// total={total}
					// pagination
					scroll={{x: 4100}}
					// callback={(pagination: any) => {
					// 	getTabelValue(formData, pagination)
					// }}
					loading={loading}
					dataSource={tableList}
				/>
				<Modal
					title="新增补扣费"
					open={visible}
					onCancel={() => {
						setCid('')
						setVisible(false)
					}}
					width={1200}
					forceRender
					onOk={() => {
						if (type === 'add') {
							onSave()
						}
						if (type === 'edit') {
							onEdit()
						}
					}}>
					{visible ? (
						// <Form
						// 	layout="horizontal"
						// 	labelCol={{flex: '140px'}}
						// 	labelAlign="right"
						// 	labelWrap
						// 	autoComplete="off"
						// 	name="PersonalInformationFom"
						// 	initialValues={initialValues}
						// 	form={form}>
						// 	<Form.Item label="code" name="ditchCode" required>
						// 		<Input></Input>
						// 	</Form.Item>
						// </Form>
						<FormV
							basicsForm={form}
							initialValues={initialValues}
							fileList={fileList}
							setFileList={setFileList}
						/>
					) : (
						<></>
					)}
				</Modal>
			</>
		</div>
	)
}

export default connect(({user}: any) => ({user}))(eidtable)
